package com.ry.chat.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ServerChannelInHandler extends ChannelInboundHandlerAdapter {


    ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        String sb = "客户已经连接" + ctx.channel().remoteAddress();
        System.out.println(sb);

//        ByteBuf byteBuf = Unpooled.buffer(sb.length());
//        byteBuf.writeBytes(sb.getBytes());
//        ctx.channel().writeAndFlush(byteBuf);

        ctx.writeAndFlush("hello!" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        // Discard the received data silently.
//        try {
//            ByteBuf in = (ByteBuf) msg;
//            byte[] bb = new byte[in.readableBytes()];
//            in.readBytes(bb);
//            String ss = new String(bb, "UTF-8");
//            System.out.println("收到[" + ctx.channel().remoteAddress() + "]消息:" +ss +"/n");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } finally {
//            ReferenceCountUtil.release(msg); // (2)
//        }
        System.out.println("收到[" + ctx.channel().remoteAddress() + "]消息:" +msg +"/n");
    }


}
